package org.misalen.web.admin.controllers;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/login")
public class LoginController extends BaseController {

	/**
	 * 登录页
	 * 
	 * @return 目标页面
	 */
	@RequestMapping(value = "", method = { RequestMethod.GET }, produces = "application/json")
	public ModelAndView loginadmin(String msg) {
		System.err.println(msg);
		ModelAndView andView = new ModelAndView("/login");
		andView.addObject("msg", msg);
		return andView;
	}

	@RequestMapping(value = "", method = { RequestMethod.POST }, produces = "application/json")
	public ModelAndView longin(@RequestParam String username, @RequestParam String password) {
		logger.info("POST请求登录");
		if (StringUtils.isEmpty(username)) {
			logger.error("用户名不能为空");
			return new ModelAndView("redirect:/login?msg=用户名不能为空");
		}
		if (StringUtils.isEmpty(password)) {
			logger.error("密码不能为空");
			return new ModelAndView("redirect:/login?msg=密码不能为空");
		}
		Subject user = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
		// 默认设置为记住密码，你可以自己在表单中加一个参数来控制
		token.setRememberMe(true);
		try {
			user.login(token);
		} catch (UnknownAccountException e) {
			logger.error("账号不存在！", e);
			return new ModelAndView("redirect:/login?msg=账号不存在");
		} catch (DisabledAccountException e) {
			logger.error("账号未启用！", e);
			return new ModelAndView("redirect:/login?msg=账号未启用");
		} catch (IncorrectCredentialsException e) {
			logger.error("密码错误！", e);
			return new ModelAndView("redirect:/login?msg=密码错误");
		} catch (RuntimeException e) {
			logger.error("未知错误,请联系管理员！", e);
			return new ModelAndView("redirect:/login?msg=未知错误,请联系管理员");
		}
		return new ModelAndView("redirect:/home/");
	}

	@RequestMapping(value = "/out", method = { RequestMethod.GET }, produces = "application/json")
	public ModelAndView longinout() {
		Subject user = SecurityUtils.getSubject();
		if (user != null) {
			user.logout();
		}
		return new ModelAndView("/login");
	}
}
